# Program to illustrate the use of user-defined functionsdef add_numbers(x, y):sum = x + yreturn sumnum1 = 5num2 = 6print("The sum is", add_numbers(num1, num2))
Output
The sum is 11
A function is a block of organised, reusable code that does one related job. Write it once, call it as often as you like.
| Kind | Who wrote it | Example |
|---|---|---|
| Built-in | Already inside Python | print(), int(), len(), sum() |
| User-defined | You, with def |
add_numbers() |
# Program to illustrate the use of user-defined functionsdef add_numbers(x, y):sum = x + yreturn sumnum1 = 5num2 = 6print("The sum is", add_numbers(num1, num2))
The sum is 11
The rules are short. def starts the definition, the header
always ends with a colon, the name follows the same rules as any
identifier, and only the indented lines belong to the function.
def <function name>([parameter1, parameter2, ...]):set of instructions to be executed[return <value>]
Anything inside [ ] is optional, so a function may take no
parameters and may return nothing.
def area(length, width):return length * widthresult = area(5, 8)print("Area of Rectangle:")print(result)
Area of Rectangle:
40
The function only runs when it is called. Defining it just teaches Python the recipe.
def multiply_by_two():number = 5result = number * 2print("Inside function:", result)multiply_by_two()print(result)
Inside function: 10
NameError: name 'result' is not defined
result is born inside the function and dies with it, so the
last line has nothing to print. Variables like this are said to be in
local scope.
number = 10def add_five():result = number + 5print("Inside function:", result)add_five()print("Outside function:", number)
Inside function: 15
Outside function: 10
A variable declared outside every function is global, so it can be read from anywhere in the program.